<template>
  <div class="app-container">
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['exam:subject-category:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
                   :loading="exportLoading"
                   v-hasPermi="['exam:subject-category:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-sort" size="mini" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 列表 -->
    <el-table v-if="refreshTable" v-loading="loading" :data="deptList" row-key="id" :default-expand-all="isExpandAll"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column prop="categoryName" label="分类名称" width="360"></el-table-column>
      <el-table-column label="分类ID" width="120" prop="id"/>
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.IS_PUBLIC" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="是否启用" width="100">
        <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['exam:subject-category:update']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-plus" @click="handleAdd(scope.row)"
                     v-hasPermi="['exam:subject-category:create']">新增
          </el-button>
          <el-button v-if="scope.row.parentId !== 0" size="mini" type="text" icon="el-icon-delete"
                     @click="handleDelete(scope.row)" v-hasPermi="['exam:subject-category:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="上级分类" prop="parentId">
          <treeselect v-model="form.parentId" :options="cateOptions" :normalizer="normalizer"
                      placeholder="选择上级分类"/>
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称"/>
        </el-form-item>
        <!--        <el-form-item label="分类描述" prop="categoryDesc">-->
        <!--          <el-input v-model="form.categoryDesc" placeholder="请输入分类描述" />-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label="父分类ID" prop="parentId">
          <el-input v-model="form.parentId" placeholder="请输入父分类ID" />
        </el-form-item> -->
        <!--        <el-form-item label="图片">-->
        <!--          <imageUpload v-model="form.photoUrl"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="99999" label="请输入排序号"></el-input-number>
        </el-form-item>
        <!--        <el-form-item label="类型" prop="type">-->
        <!--          <el-radio-group v-model="form.type">-->
        <!--            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.IS_PUBLIC)"-->
        <!--                      :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}-->
        <!--            </el-radio>-->
        <!--          </el-radio-group>-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label="创建时间" prop="createDate">
          <el-date-picker clearable v-model="form.createDate" type="date"  value-format="timestamp" placeholder="选择创建时间" />
        </el-form-item>
        <el-form-item label="修改人" prop="modifier">
          <el-input v-model="form.modifier" placeholder="请输入修改人" />
        </el-form-item>
        <el-form-item label="修改时间" prop="modifyDate">
          <el-date-picker clearable v-model="form.modifyDate" type="date" value-format="timestamp" placeholder="选择修改时间" />
        </el-form-item>
        <el-form-item label="删除标记" prop="delFlag">
          <el-select v-model="form.delFlag" placeholder="是否删除">
            <el-option  v-for="dict in this.getDictDatas(DICT_TYPE.IS_DELETE)" :key="dict.value"  :value="dict.value" :label="dict.label"/>
          </el-select>
        </el-form-item>
        <el-form-item label="系统编号" prop="applicationCode">
          <el-input v-model="form.applicationCode" placeholder="请输入系统编号" />
        </el-form-item>-->
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.IS_TRUE)"
                      :key="dict.value" :label="parseInt(dict.value)">{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createSubjectCategory,
  updateSubjectCategory,
  deleteSubjectCategory,
  getSubjectCategory,
  getSubjectCategoryPage,
  exportSubjectCategoryExcel,
  getSimpleList
} from "@/api/examination/subjectCategory";
import ImageUpload from '@/components/ImageUpload';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SubjectCategory",
  components: {
    ImageUpload,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 题目分类列表
      list: [],
      deptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        categoryName: null,
        type: null,
        status: null,
      },
      // 表单参数
      form: {
        status: 0
      },
      // 表单校验
      rules: {
        parentId: [{required: true, message: "上级分类", trigger: "blur"}],
        categoryName: [{required: true, message: "分类名称", trigger: "blur"}],
        // type: [{required: true, message: "类型", trigger: "blur"}],
        status: [{required: true, message: "类型", trigger: "blur"}],
        // sort: [{required: true, message: "排序不能为空", trigger: "blur"}],
      },
      //分类树
      cateOptions: [],
      categoryName: undefined,
      defaultProps: {
        children: "children",
        label: "categoryName"
      },
      // 是否展开，默认全部展开
      isExpandAll: true,
    };
  },
  watch: {
    // 根据名称筛选部门树
    categoryName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getSubjectCategoryPage(this.queryParams).then(response => {
        for (let i = 0; i < response.data.list.length; i++) {
          response.data.list[i].id = parseInt(response.data.list[i].id);
          response.data.list[i].parentId = parseInt(response.data.list[i].parentId);
        }
        this.deptList = this.handleTree(response.data.list, "id");
        this.total = parseInt(response.data.total);
        this.loading = false;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.getList();
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        categoryName: undefined,
        categoryDesc: undefined,
        parentId: undefined,
        photoUrl: undefined,
        sort: undefined,
        type: undefined,
        createDate: undefined,
        modifier: undefined,
        modifyDate: undefined,
        delFlag: undefined,
        applicationCode: undefined,
        status: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row !== undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加题目分类";
      getSimpleList().then(response => {
        // 处理 cateOptions 参数
        // this.cateOptions = [];
        // this.cateOptions.push(...this.handleTree(response.data, "id"));
        for (let i = 0; i < response.data.length; i++) {
          response.data[i].id = parseInt(response.data[i].id);
          response.data[i].parentId = parseInt(response.data[i].parentId);

        }
        this.cateOptions = this.handleTree(response.data, "id");
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getSubjectCategory(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改题目分类";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateSubjectCategory(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createSubjectCategory(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除题目分类编号为"' + id + '"的数据项?').then(function () {
        return deleteSubjectCategory(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有题目分类数据项?').then(() => {
        this.exportLoading = true;
        return exportSubjectCategoryExcel(params);
      }).then(response => {
        this.$download.excel(response, '题目分类.xls');
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children
      };
    },
  }
};
</script>
